package com.atguigu.day04;

import com.alibaba.fastjson.JSON;
import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.connectors.redis.RedisSink;
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommand;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommandDescription;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisMapper;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class Flink02_Sink_Custom {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.从端口读取数据并转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> streamOperator = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });

        //TODO 3.将数据通过自定义Sink写入MySQL
        streamOperator.addSink(new MySink());

        env.execute();
    }

//    public static class MySink implements SinkFunction<WaterSensor>{
    public static class MySink extends RichSinkFunction<WaterSensor> {
    Connection connection;
    PreparedStatement pstm;


    @Override
    public void open(Configuration parameters) throws Exception {
        System.out.println("创建链接");
        //1.获取连接
       connection = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/test?useSSL=false","root","123456");
        //2.获取语句预执行者
        pstm = connection.prepareStatement("insert into sensor values (?,?,?)");
    }

    @Override
    public void close() throws Exception {
        System.out.println("关闭链接");
        pstm.close();
        connection.close();
    }

    @Override
        public void invoke(WaterSensor value, Context context) throws Exception {


            pstm.setString(1, value.getId());
            pstm.setLong(2, value.getTs());
            pstm.setInt(3, value.getVc());

            pstm.execute();



        }
    }
}
